<template>
  <div class="app-container">

    <!-- 顶部搜索 -->
    <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="微信OpenID" prop="openid">
        <el-input
          v-model="queryParams.openid"
          placeholder="请输入微信OpenID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信UnionID" prop="unionid">
        <el-input
          v-model="queryParams.unionid"
          placeholder="请输入微信UnionID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入真实姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="微信OpenID" prop="openid">
            <el-input v-model="queryParams.openid" placeholder="请输入微信OpenID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="queryParams.realName" placeholder="请输入真实姓名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="微信UnionID" prop="unionid">
            <el-input v-model="queryParams.unionid" placeholder="请输入微信UnionID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门ID" prop="deptId">
            <el-input v-model="queryParams.deptId" placeholder="请输入部门ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="search-btn">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按键 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['guestInfo:guest:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['guestInfo:guest:edit']">修改</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['guestInfo:guest:remove']">删除</el-button>
      </el-col>

      <!-- v-hasPermi 是权限相关的配置，记得改一下 -->
      <!-- <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['collegeManage:studentBase:import']">导入</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Upload" @click="handleImport"
          v-hasPermi="['guestInfo:guest:add']">导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['guestInfo:guest:export']">导出</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="guestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="顾客ID" align="center" prop="guestId" />
      <el-table-column label="微信OpenID" align="center" prop="openid" />
      <el-table-column label="微信UnionID" align="center" prop="unionid" />
      <el-table-column label="真实姓名" align="center" prop="realName" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="头像URL" align="center" prop="avatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="逻辑删除" align="center" prop="delFlag">
        <template #default="scope">
          <dict-tag :options="del_flag" :value="scope.row.delFlag" />
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" align="center" prop="loginIp" />
      <el-table-column label="最后登录时间" align="center" prop="loginDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['guestInfo:guest:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['guestInfo:guest:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改顾客信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="guestRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信OpenID" prop="openid">
          <el-input v-model="form.openid" placeholder="请输入微信OpenID" />
        </el-form-item>
        <el-form-item label="微信UnionID" prop="unionid">
          <el-input v-model="form.unionid" placeholder="请输入微信UnionID" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="头像URL" prop="avatar">
          <image-upload v-model="form.avatar" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逻辑删除" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除">
            <el-option v-for="dict in del_flag" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入最后登录IP" />
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker clearable v-model="form.loginDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelopen" width="500px" append-to-body>

      <!-- <el-upload class="upload-demo" drag :action="uploadExcelUrl" :headers="headers" :limit="1" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" :before-upload="handleBeforeUpload" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload> -->

      <el-upload class="upload-demo" ref="upload" :action="uploadExcelUrl" :headers="headers" :limit="1"
        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="handleBeforeUpload"
        :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :auto-upload="true">

        <el-button size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>

        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>

      <!-- <el-upload class="upload-demo" :action="uploadExcelUrl" :headers="headers" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" :before-upload="handleBeforeUpload" :on-remove="handleRemove"
        :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed" :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload> -->


    </el-dialog>

  </div>
</template>

<script setup name="Guest">
import { listGuest, getGuest, delGuest, addGuest, updateGuest } from "@/api/guestInfo/guest"
// 导入getToken方法
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance()
const { sys_user_sex, sys_normal_disable } = proxy.useDict('sys_user_sex', 'sys_normal_disable')

const guestList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    openid: null,
    unionid: null,
    realName: null,
    mobile: null,
    idCard: null,
    gender: null,
    status: null,
    deptId: null,
    userId: null
  },

  // 表单校验
  rules: {
    openid: [
      { required: true, message: "微信OpenID不能为空", trigger: "blur" }
    ],
    realName: [
      { required: true, message: "真实姓名不能为空", trigger: "blur" }
    ],
    mobile: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的11位手机号码",
        trigger: ["blur", "change"]
      }
    ],
    idCard: [
      { required: true, message: "身份证号不能为空", trigger: "blur" },
      {
        pattern: /(^\d{15}$)|(^\d{17}(\d|X|x)$)/,
        message: "请输入正确的15位或18位身份证号码",
        trigger: ["blur", "change"]
      }
    ],
    // mobile: [
    //   { required: true, message: "手机号不能为空", trigger: "blur" }
    // ],
    // idCard: [
    //   { required: true, message: "身份证号不能为空", trigger: "blur" }
    // ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询顾客信息列表 */
function getList() {
  loading.value = true
  listGuest(queryParams.value).then(response => {
    guestList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    guestId: null,
    openid: null,
    unionid: null,
    realName: null,
    mobile: null,
    email: null,
    idCard: null,
    avatar: null,
    gender: null,
    status: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    deptId: null,
    userId: null
  }
  proxy.resetForm("guestRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guestId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加顾客信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _guestId = row.guestId || ids.value
  getGuest(_guestId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改顾客信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["guestRef"].validate(valid => {
    if (valid) {
      if (form.value.guestId != null) {
        updateGuest(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGuest(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _guestIds = row.guestId || ids.value
  proxy.$modal.confirm('是否确认删除顾客信息编号为"' + _guestIds + '"的数据项？').then(function () {
    return delGuest(_guestIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导入按钮操作 */
const excelopen = ref(false)
function handleImport() {
  excelopen.value = true;

}
/** 上传Excel文件操作 */
const uploadRef = ref({});
function submitUpload() {
  uploadRef.value.submit();
}
// 上传地址
const uploadExcelUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
// 上传请求头
const headers = ref({ Authorization: "Bearer " + getToken() });

// 上传成功回调
function handleUploadSuccess(res, file) {
  proxy.$modal.closeLoading();
  if (res.code === 200) {
    proxy.$modal.msgSuccess("上传Excel文件成功");
    excelopen.value = false;
    getList();
    // uploadList.value.push({ name: res.fileName, url: res.fileName });
    // uploadedSuccessfully();
  } else {
    // number.value--;
    // proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
    // proxy.$refs.imageUpload.handleRemove(file);
    // uploadedSuccessfully();
  }
  uploadRef.value.clearFiles();
  // proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传Excel文件失败:" + error.message);
  // proxy.$modal.closeLoading();
  uploadRef.value.clearFiles();
}

// 上传Excel文件前的校验
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  // limit: {
  //   type: Number,
  //   default: 5,
  // },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['xls', 'xlsx']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
  // 是否显示提示
  // isShowTip: {
  //   type: Boolean,
  //   default: true
  // },
});
// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  }
  // else {
  //   isExcel = file.type.indexOf("image") > -1;
  // }
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传Excel文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  return true;
  // number.value++;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('guestInfo/guest/export', {
    ...queryParams.value
  }, `guest_${new Date().getTime()}.xlsx`)
}

getList()
</script>
